package com.mulanweb.api.module.controller.seller;

import com.jfinal.kit.StrKit;
import com.mulanweb.api.module.controller.BaseController;
import com.mulanweb.api.module.model.*;
import com.mulanweb.db.common.Constant;
import com.mulanweb.handler.wechat.SentModelMessageHandler;
import com.mulanweb.utils.AseUtils;
import com.mulanweb.utils.DateUtil;
import com.mulanweb.utils.RandomUtil;
import com.mulanweb.validator.annotation.ValidateForm;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2016/11/8 0008.
 */
public class VerifyController extends BaseController{

    @ValidateForm
    public void codeVerify()throws Exception{
        String verifyCode = getPara("verifyCode");
        Integer typeId = getParaToInt("typeId");
        Long sellerId = getSessionAttr("sellerId");
        String encodeVerifyCode =  AseUtils.aesEncrypt(verifyCode,Constant.XinXiLan.ORDER_AES_KEY);
        Order order = Order.dao.findFirst("SELECT * FROM `order` WHERE type_id=? AND verify_code=?",typeId,encodeVerifyCode);
        if(order == null){
            returnJson(0,Constant.PromptMessage.VERIFY_FAIL);
            return;
        }
        boolean tag = true ;
        if(typeId == 23){
            Date createTime = order.getCreateTime();
            Date date=new Date();//获取当前时间
            Calendar   calendar   =Calendar.getInstance();
            calendar.setTime(createTime);
            calendar.add(calendar.DATE,Constant.XinXiLan.VERIFY_CODE_OVERTIME);//把日期往后增加一天.整数往后推,负数往前移动
            Date overTime = calendar.getTime();   //这个时间就是日期往后推一天的结果
            //验证码超过三十天，已过期
            if(date.getTime() > overTime.getTime()){
                tag = false ;
            }
        }

        //4表示订单已支付，13表示验证码等待验证
        if(StrKit.notNull(order)
                && order.getStatusId() == 4
                && order.getVerifyCodeStatus() == 13
                && order.getSellerId()==sellerId
                && tag ){
            order.setStatusId(7L);//订单状态等于7，表示已验证
            order.setVerifyCodeStatus(15L);//订单验证码状态等于15，表示已使用
            order.setVerifyTime(new Date());
            order.setVerifySellerId(sellerId);
            if(order.update()){
                String title = "........" ;
                if(typeId ==23){
                    Ticket ticket = Ticket.dao.findById(order.getTargetId());
                    title = ticket.getTitle();
                }else if(typeId ==24){
                    Chartered chartered = Chartered.dao.findById(order.getTargetId());
                    title = chartered.getTitle();
                }
                SentModelMessageHandler.sentVerifyOrderModel(title,verifyCode,order.getAmount(),getSessionAttr("openId"));
                returnJson(1,Constant.PromptMessage.VERIFY_SUCCESS(order.getAmount()));
            }else{
                returnFailureJson();
            }
        }else{
            //验证失败
            returnJson(0,Constant.PromptMessage.VERIFY_FAIL);
        }
    }
}
